﻿define(function (require, exports, module) {
    var ImageStorage = require('util/imageStorage');
    var Canvas = require('util/canvas');
    var Config = require('util/config');
    var ILogin = require('iLogin');

    exports.loadAsync = eval(Wind.compile('async', function () {
        Canvas.clear();
        $await(ILogin.renderAsync());

        var loginImage = Canvas.get('#login')[0];
        loginImage.on('click', function () {
            m_okClickAsync(this).start();
        });

        Canvas.get('#quit').on('click', function () {
            window.opener = null;
            window.open(null, '_self');
            window.close();
        });

        Canvas.get('#failure').on('click', function () {
            this.getParent().hide();
            $('#txtName').show();
            $('#txtPwd').show();
            loginImage.show();
        });
    }));

    var m_okClickAsync = eval(Wind.compile('async', function (_this) {
        var txtName = $('#txtName'), txtPwd = $('#txtPwd');
        if ('' == txtName.val().trim() || '' == txtPwd.val().trim()) {
            txtName.focus();
            return;
        }
        var form = $('#loginForm');
        _this.hide();
        var response = $await(formAjaxTask(form));
        if (response.success) {
            form.remove();
            var RoleManager = require('newRole/roleManager');
            RoleManager.setBackCallback(function () {
                exports.loadAsync().start();
            });
            RoleManager.setData(response.roles);
            RoleManager.loadAsync().start();
            var Error = require('error');
            Error.setErrorCallback(function () {
                exports.loadAsync().start();
            });
        }
        else {
            txtName.hide();
            txtPwd.hide();
            var failureGroup = Canvas.get('#failureGroup')[0];
            failureGroup.show();
            failureGroup.getLayer().draw();
        }
    }));

    function formAjaxTask(form, options) {
        return Wind.Async.Task.create(function (t) {
            form.ajaxSubmit({
                cache: false,
                dataType: 'json',
                success: function (data, textStatus, jqXHR) {
                    t.complete('success', data);
                }
            });
        });
    };
});